package com.lovezy.platform.borrow.form;

import com.lovezy.platform.borrow.enums.BorrowApplyTypeEnum;
import com.lovezy.platform.borrow.exception.BorrowException;
import com.lovezy.platform.borrow.model.BorrowApply;
import com.lovezy.platform.borrow.model.MyGame;
import com.lovezy.platform.borrow.service.MyGameService;
import com.lovezy.platform.core.base.enums.StatusEnum;
import com.lovezy.platform.core.exception.RequestErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.lovezy.platform.borrow.exception.BorrowExpcetionEnum.BORROW_MYGAME_NOT_FOUND;
import static com.lovezy.platform.core.utils.ObjectUtil.nonNull;

/**
 * 借还表单 管理
 * Created by jin on 2017/11/15.
 */
@Component
public class BorrowFormManager {

    @Autowired
    private MyGameService myGameService;

    public BorrowApply toBorrowApply(BorrowForm form) {
        BorrowApply apply = new BorrowApply();
        Integer myGameId = form.getMyGameId();
        String memberId = form.getMemberId();
        nonNull(myGameId);
        apply.setMyGameId(myGameId);
        MyGame myGame = myGameService.selectById(myGameId);
        if (myGame == null) {
            throw new BorrowException(BORROW_MYGAME_NOT_FOUND);
        }
        apply.setOwnId(myGame.getMemberId());
        if (form.getShopId() != null) {
            apply.setShopId(form.getShopId());
            apply.setType(BorrowApplyTypeEnum.SHOP.value());
        } else if (memberId != null) {
            apply.setMemberId(memberId);
            apply.setType(BorrowApplyTypeEnum.USER.value());
        } else {
            throw new RequestErrorException();
        }
        Date now = new Date();
        apply.setPrice(myGame.getPrice());
        apply.setGmtCreate(now);
        apply.setGmtModify(now);
        apply.setStatus(StatusEnum.NORMAL.value());
        return apply;
    }
}
